package com.czkspringcloud.controller;

import com.czkspringcloud.config.MyLinkedBlockingQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 动态线程池的测试
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/25 15:16
 */
@RestController
@RequestMapping("/change")
@RefreshScope
public class ChangeThreadPollArgsController {
    @Value(
            "${core.size}"
    )
    private Integer coreSize;
    @Value(
            "${max.size}"
    )
    private Integer maxSize;
    @Value(
            "${queue.size}"
    )
    private Integer queueSize;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 改变线程池参数
     * 对单例对象进行设置，需要有线程安全问题
     *
     * @return
     */
    @GetMapping("/set")
    public synchronized String change() {
        // 修改核心线程
        System.out.println("coreSize= " + coreSize);
        threadPoolExecutor.setCorePoolSize(coreSize);
        // 修改最大线程
        System.out.println("maxSize= " + maxSize);
        threadPoolExecutor.setMaximumPoolSize(maxSize);
        // 修改队列大小
        System.out.println("queueSize= " + queueSize);
        MyLinkedBlockingQueue<Runnable> queue = (MyLinkedBlockingQueue) threadPoolExecutor.getQueue();
        queue.setCapacity(queueSize);
        return "设置成功";
    }

    @GetMapping("/cat")
    public Map<String, Integer> getInformations() {
        Map<String, Integer> map = new HashMap<>();
        map.put("coreSize", threadPoolExecutor.getCorePoolSize());
        map.put("maxSize", threadPoolExecutor.getMaximumPoolSize());
        map.put("queueSize", ((MyLinkedBlockingQueue) threadPoolExecutor.getQueue()).getCapacity());
        return map;
    }
}
